<template>
  <div class="history-data-container">
    <div class="history-data-box">
      <div class="history-data-box-top">
        <div class="device-model-info">
          <div class="device-name-set">
            <p>{{ conditionData.deviceName }}</p>
            <van-button @click="showSet = true">重新设置</van-button>
          </div>
          <div class="model-name-num">
            <span>物模型：{{ conditionData.deviceModelName }}</span>
            <span>编号：{{ conditionData.deviceNumber }}</span>
          </div>
        </div>
        <p class="date-box">起止时间：{{ conditionData.startTime }} - {{ conditionData.endTime }}</p>
        <div class="nav-box">
          <ul class="nav-content">
            <li
              :class="{active: showDateRes}"
              @click="changeNav(0)"
            >按时间</li>
            <!-- <li
              :class="{active: !showDateRes}"
              @click="changeNav(1)"
            >按变量</li> -->
          </ul>
          <span class="result-box">共{{ total }}条历史数据</span>
        </div>
      </div>

      <div
        class="date-result-wrapper scroll-box"
        v-show="showDateRes"
        @scroll="scrollFn"
      >
        <div
          class="result-item"
          v-for="(item, keys) in filterHistoryData"
          :key="keys"
        >
          <template v-for="(ii, key, n) in item">
            <p
              class="result-date"
              :key="n"
            >{{ key }}</p>
            <ul
              class="result-data"
              :key="key"
            >
              <li
                v-for="(subItem, idx) in ii"
                :key="idx"
              >
                <span class="color-deep-gray">{{ subItem.name }}</span>
                <span>{{ subItem.value }} {{ subItem.unit }}</span>
              </li>
              <!-- <li>
                <span class="color-deep-gray">空压机出口温度</span>
                <span>1234.5 度</span>
              </li>
              <li>
                <span class="color-deep-gray">空压机出口温度</span>
                <span>1234.5 度</span>
              </li> -->
            </ul>
          </template>
        </div>
      </div>

      <!-- <div
        class="var-result-wrapper"
        v-show="!showDateRes"
      >
        <van-tabs
          v-model="activeTab"
          :ellipsis="false"
        >
          <van-tab title="变量名称文字">
            <List />
          </van-tab>
          <van-tab title="空压机出口温度">
            <List />
          </van-tab>
          <van-tab title="空压机一号电机温度">
            <List />
          </van-tab>
          <van-tab title="空压机出口温度">
            <List />
          </van-tab>
        </van-tabs>
      </div> -->
    </div>

    <div class="choose-box border-top">
      <van-button
        plain
        block
        @click="openVarBox"
      >选择变量</van-button>
    </div>

    <van-popup
      v-model="showVar"
      position="bottom"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ conditionData.deviceModelName || '' }}</span>
          <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarData.length }}</span>/5）</p>
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKey"
              shape="round"
              placeholder="输入变量名称查找"
              clearable
              @search="handleSearch"
              @clear="handleClear"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="(item, index) in filterVarList"
            :key="item.vname"
            :class="{'color-primary': item.checked}"
            @click="selectVar(item, index)"
          >
            <span>{{ item.vname }}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelect">取消</li>
          <li
            class="color-primary"
            @click="confirmSelect"
          >确定</li>
        </ul>
      </div>
    </van-popup>

    <ConditionSet
      v-show="showSet"
      @submit="submitConditionSet"
      @cancel="cancelConditionSet"
    />
  </div>
</template>

<script>
import { Button, Tab, Tabs, Search, Popup } from 'vant';
// import List from './component/List.vue';
import ConditionSet from './component/ConditionSet.vue';
import { getHistoryDataList, getModelVariable } from '@/api/historyData.js';

export default {
  name: 'HistoryData',
  components: {
    [Button.name]: Button,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Search.name]: Search,
    [Popup.name]: Popup,
    // List,
    ConditionSet
  },
  data() {
    return {
      showSet: false,
      activeTab: 0,
      showDateRes: false,
      showVar: false,
      searchKey: '',
      conditionData: {},
      total: 0,
      varTotal: 0,
      varList: [],
      filterVarList: [],
      deviceModelId: '',
      deviceModelName: '',
      chooseVarData: [],
      oldChooseVarData: [],
      pageIndex: 1,
      pageSize: 15,
      allModelVariableData: [],
      historyData: {},
      filterHistoryData: []
    };
  },
  created() {
    let conditionStorageData = localStorage.getItem('conditionData');
    if (conditionStorageData) {
      this.conditionData = JSON.parse(conditionStorageData);
      this.getAllModelVariable();
    } else {
      this.showSet = true;
    }
  },
  methods: {
    // 关闭条件设置
    cancelConditionSet() {
      if (this.conditionData.deviceModelId) {
        this.showSet = false;
      } else {
        this.$router.back();
      }
    },
    // 提交条件设置
    submitConditionSet(data) {
      this.conditionData = data;
      this.showSet = false;
      this.pageIndex = 1;
      this.historyData = {};
      this.filterHistoryData = [];
      this.getAllModelVariable();
    },
    // 切换导航
    changeNav(index) {
      if (index === 0) {
        this.showDateRes = true;
      } else {
        this.showDateRes = false;
      }
    },
    // 获取物模型的所有变量
    getAllModelVariable() {
      getModelVariable({
        id: this.conditionData.deviceModelId
      })
        .then(res => {
          if (res.data && res.data.length) {
            this.allModelVariableData = res.data;
          }
        })
        .then(() => {
          this.getHistoryDataList();
        });
    },
    // 获取历史数据
    getHistoryDataList() {
      let s = {
        hours: 3600,
        minutes: 60,
        seconds: 1
      };

      let startTime = new Date(this.conditionData.startTime).getTime() / 1000;
      let endTime = new Date(this.conditionData.endTime).getTime() / 1000;

      let params = {
        start_time: startTime + this.pageSize * (this.pageIndex - 1) * s[this.conditionData.dimension], // 起始时间
        end_time: endTime, // 结束时间
        dimension: this.conditionData.dimension, // 时、分、秒
        param: JSON.stringify(this.conditionData.params)
      };
      if (params.end_time > params.start_time + (this.pageSize - 1) * s[this.conditionData.dimension]) {
        params.end_time = params.start_time + (this.pageSize - 1) * s[this.conditionData.dimension];
      }

      this.total = Math.floor((endTime - startTime) / s[this.conditionData.dimension]) + 1;

      getHistoryDataList(params).then(res => {
        Object.keys(res.data).map(key => {
          let data = {};
          data[key] = [];
          let result = res.data[key];

          Object.keys(result).map(itemKey => {
            let item = this.handleData(itemKey);
            if (item) {
              data[key].push({
                name: item.vname,
                unit: item.vcompany,
                value: result[itemKey].value === undefined ? '-' : result[itemKey].value
              });
            }
          });
          this.historyData = Object.assign(this.historyData, data);
          this.$forceUpdate();
        });

        this.showDateRes = true;
        if (JSON.stringify(this.historyData) === '{}') {
          this.total = 0;
        }
        let arr = [];
        for (let i in this.historyData) {
          let o = {};
          o[i] = this.historyData[i];
          arr.push(o);
        }
        this.filterHistoryData = JSON.parse(JSON.stringify(arr));
      });
    },
    // 处理数据
    handleData(key) {
      let res = this.allModelVariableData.filter(item => {
        return item.vk === key;
      });
      return res[0];
    },
    // 打开选择变量
    openVarBox() {
      if (this.conditionData.deviceModelId) {
        this.showVar = true;
        this.getModelVariable();
      } else {
        this.$toast('请先选择设备');
      }
    },
    // 搜索变量
    handleSearch() {
      let filterArr = this.varList.filter(item => {
        return item.vname.indexOf(this.searchKey) !== -1;
      });
      this.filterVarList = filterArr;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 清空搜索
    handleClear() {
      this.filterVarList = this.varList;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 选择变量
    selectVar(item, index) {
      if (!item.checked) {
        if (this.chooseVarData.length === 5) {
          this.$toast('最多选择5个变量');
          return;
        }
      }

      item.checked = !item.checked;
      this.$forceUpdate();
      if (item.checked) {
        this.chooseVarData.push(item);
      } else {
        this.chooseVarData.map((ii, idx) => {
          if (ii.vname === item.vname) {
            this.chooseVarData.splice(idx, 1);
          }
        });
      }
    },
    // 取消变量选择
    cancelSelect() {
      this.showVar = false;
    },
    // 确定变量选择
    confirmSelect() {
      let params = [];
      this.chooseVarData.map(item => {
        let obj = {
          product_id: this.conditionData.deviceModelId + '',
          device_id: this.conditionData.deviceValue + '',
          point: item.vk,
          type: item.vtype
        };
        params.push(obj);
      });
      this.conditionData.params = params;
      localStorage.setItem('conditionData', JSON.stringify(this.conditionData));
      this.pageIndex = 1;
      this.historyData = {};
      this.filterHistoryData = [];
      this.showVar = false;
      this.getHistoryDataList();
    },
    // 获取物模型变量
    getModelVariable() {
      getModelVariable({
        id: this.conditionData.deviceModelId
      }).then(res => {
        if (res.data && res.data.length) {
          this.varList = res.data;
          this.varList.map(item => {
            item.checked = false;
          });
          this.filterVarList = JSON.parse(JSON.stringify(this.varList));
          if (this.chooseVarData.length) {
            this.chooseVarData.map(item => {
              this.filterVarList.map(ii => {
                if (ii.vname === item.vname) {
                  ii.checked = item.checked;
                }
              });
            });
          }
        }
      });
    },
    // 滚动事件
    scrollFn(e) {
      let scrollTop = document.querySelector('.date-result-wrapper').scrollTop;
      let clientHeight = document.querySelector('.date-result-wrapper').clientHeight;
      let scrollHeight = document.querySelector('.date-result-wrapper').scrollHeight;

      if (scrollTop + clientHeight >= scrollHeight) {
        this.$debounceFn(this.onLoadMore, 300);
      }
    },
    // 加载更多
    onLoadMore() {
      if (this.filterHistoryData.length < this.total) {
        // 异步更新数据
        setTimeout(() => {
          this.pageIndex++;
          this.getHistoryDataList();
        }, 100);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.history-data-container {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .history-data-box {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 0;

    .history-data-box-top {
      .device-model-info {
        width: 100%;
        padding: 0.32rem 0.426667rem;
        background-color: #fff;
        border-bottom: 1px solid var(--border-color);

        .device-name-set {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          margin-bottom: 0.213333rem;

          p {
            font-size: 0.4rem;
          }

          .van-button {
            width: 2.293333rem;
            height: 0.853333rem;
            padding: 0;
            color: #fff;
            border-radius: 0.08rem;
            border-color: var(--color-primary);
            background-color: var(--color-primary);
          }
        }

        .model-name-num {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: var(--color-deep-gray);
          font-size: 0.346667rem;
        }
      }

      .date-box {
        padding: 0.32rem 0.426667rem;
        font-size: 0.346667rem;
        background-color: #fff;
      }

      .nav-box {
        display: flex;
        justify-content: space-between;
        padding: 0.213333rem 0.426667rem;

        .nav-content {
          display: flex;

          li {
            margin-left: 0.426667rem;
            color: var(--color-gray);
            font-size: 0.32rem;

            &:first-of-type {
              margin-left: 0;
            }

            &.active {
              color: var(--color-primary);
            }
          }
        }

        .result-box {
          color: var(--color-deep-gray);
          font-size: 0.32rem;
        }
      }
    }

    .date-result-wrapper {
      flex: 1;

      .result-item {
        margin-bottom: 0.213333rem;

        .result-date {
          position: relative;
          display: flex;
          align-items: center;
          width: 100%;
          height: 0.853333rem;
          padding-left: 0.266667rem;
          color: #85aeff;
          font-size: 0.32rem;
          border-bottom: 1px solid var(--border-color);
          background-color: #fff;

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 0.053333rem;
            height: 100%;
            background-color: #85aeff;
          }
        }

        .result-data {
          width: 100%;
          padding: 0 0.426667rem;
          background-color: #fff;

          li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            height: 1.013333rem;
            font-size: 0.373333rem;
            border-bottom: 1px solid var(--border-color);

            &:last-of-type {
              border-bottom: 0;
            }
          }
        }
      }
    }

    .var-result-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      height: 0;

      ::v-deep .van-tabs {
        display: flex;
        flex-direction: column;
        height: 100%;

        .van-tabs__wrap {
          flex-shrink: 0;
          height: 0.96rem;
          border-bottom: 1px solid var(--border-color);

          .van-tab__text {
            font-size: 0.32rem;
          }
        }

        .van-tabs__content {
          flex: 1;
          height: 0;

          .van-tab__pane {
            height: 100%;
          }
        }
      }
    }
  }

  .choose-box {
    flex-shrink: 0;
    width: 100%;
    height: 1.493333rem;
    padding: 0.213333rem 0.426667rem;
    background-color: #fff;

    .van-button {
      color: var(--color-primary);
      border-color: var(--color-primary);

      &::before {
        background-color: var(--color-primary);
      }
    }
  }

  .van-popup--bottom {
    border-top-left-radius: 0.426667rem;
    border-top-right-radius: 0.426667rem;

    .var-box {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;

      .var-box-header {
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.213333rem;
        padding: 0 0.426667rem;
        padding-top: 0.426667rem;

        .model-name {
          margin-right: 0.266667rem;
          font-size: 0.426667rem;
          line-height: 0.533333rem;
        }

        .model-choose {
          flex-shrink: 0;
          color: var(--color-deep-gary);
          font-size: 0.32rem;
        }
      }

      .var-search-box {
        flex-shrink: 0;
        margin-bottom: 0.213333rem;
        border-bottom: 1px solid var(--border-color);
      }

      .var-list {
        flex: 1;
        width: 100%;
        padding: 0 0.426667rem;

        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0.32rem 0;
          font-size: 0.373333rem;
          border-bottom: 1px solid var(--border-color);

          &:last-of-type {
            border-bottom: 0;
          }
        }
      }

      .operate-box {
        flex-shrink: 0;
        display: flex;
        width: 100%;
        height: 1.28rem;
        border-top: 1px solid var(--border-color);

        li {
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 50%;
          font-size: 0.426667rem;

          &:first-of-type {
            &::after {
              content: '';
              position: absolute;
              top: 0;
              right: 0;
              width: 1px;
              height: 100%;
              background-color: var(--border-color);
            }
          }
        }
      }
    }
  }
}
</style>